<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandler" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      :isSelectColumn="false"
      columnsRef="maintenanceBoutiqueasda"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" @click="groupHandle">班组统计</el-button>
      </template>
    </FilterTable>
    <!-- 打印组件 -->
    <BasePrint ref="Salesprint" :data="groupPrintList" template="boutique/report/maintenanceBoutiqueSelect/templateGroup" />
  </div>
</template>

<script>
/**
 * 维护装饰项目查询报表
 */
// 数据字典/按钮权限
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { confirmAction, notifyAction } from '@/utils';
import { getAllUser } from '@/api/part/common';
import { getList, getGroupList } from '@/api/part/qualityManagement/report';
import { toggleMixin } from './dict.js';
export default {
  name: 'jpwhcx',
  components: {},
  mixins: [dictionary, authority, toggleMixin],
  data() {
    this.BaseTable = null;
    this.selectedRow = null;
    this.editData = {};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getList,
      fetchParams: { xhrAbort: true },
      isChoice: true, // 按钮是否可以选择
      reviewCode: new Map([
        [10041001, '已审核'],
        [10041002, '未审核']
      ]),
      userList: [],
      queryParam: {}, // 查询参数
      printBtn: false,
      groupPrintList: {} // 打印数据
    };
  },
  created() {
    this.getUserList();
    // console.log(this.userList, this.reviewCode);
  },
  methods: {
    // 处理数据
    handlePrintData(val) {
      // 处理班组数组
      let groupArr = [];
      val.map(item => {
        if (!groupArr.find(item2 => item2.code == item.bzCode)) {
          groupArr.push({ name: item.bzName, code: item.bzCode });
        }
      });

      let printObj = {};
      let total = 0;
      groupArr.map(item => {
        printObj[item.code] = {};
        printObj[item.code].projectList = [];
        printObj[item.code].totalAmount = 0;
        val.map(item2 => {
          if (item2.bzCode == item.code) {
            printObj[item.code].projectList.push({
              name: item2.proName,
              amount: parseFloat(item2.workHoursStatistics).toFixed(2)
            });
            printObj[item.code].totalAmount += item2.workHoursStatistics ? item2.workHoursStatistics * 1 : 0;
          }
        });
        printObj[item.code].totalAmount = printObj[item.code].totalAmount.toFixed(2);
        total += parseFloat(printObj[item.code].totalAmount);
      });

      return {
        groupArr,
        printObj,
        total: total.toFixed(2)
      };
    },
    // 班组统计打印
    async groupHandle() {
      let res = await getGroupList(this.queryParam);
      if (res.resultCode == 200) {
        let printData = this.handlePrintData(res.data);
        console.log(printData, '打印的数据');
        this.groupPrintList = printData;

        // 打印
        this.printBtn = true;
        this.$nextTick(() => {
          this.$refs.Salesprint.EXCUTE_PRINT();
        });
        this.printBtn = false;
      }
    },
    async getUserList() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        res.data.map(e => {
          this.userList[e.userId] = e.employeeName;
        });
      }
    },
    createTopFilters() {
      return [
        {
          type: 'RANGE_DATE',
          label: '派工日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'orderDateBegin|orderDateEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '审核日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'reviewDateBegin|reviewDateEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'balanceDateBegin|balanceDateEnd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '装饰派工单号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工单状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('9704'),
          dictItems: this.createDictList('9704'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '9704')}</span>;
          }
        },
        {
          title: '牌照号',
          dataIndex: 'licenseTag',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'customerNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作员',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.createdBy]}</span>;
          }
        },
        {
          title: '结算员',
          dataIndex: 'balanceHandler',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.balanceHandler]}</span>;
          }
        },
        {
          title: '审核标识',
          dataIndex: 'isReviewed',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.auditDictList(),
          render: props => {
            return <span>{this.reviewCode.get(props.row.isReviewed)}</span>;
          }
        },
        {
          title: '审核员',
          dataIndex: 'reviewer',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.reviewer]}</span>;
          }
        },
        {
          title: '派工日期',
          dataIndex: 'orderDate',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '审核日期',
          dataIndex: 'reviewDate',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '结算日期',
          dataIndex: 'balanceTime',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '装饰项目代码',
          dataIndex: 'proCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '装饰项目名称',
          dataIndex: 'proName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工时费',
          dataIndex: 'manhaurFee',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },

    changeHandler(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign({}, { xhrAbort: false }, val);
      this.queryParam = val;
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      console.log(rows[0]);
      this.selectedRow = rows[0];
    },

    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },

    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    }
  }
};
</script>

<style lang="less" scoped></style>
